
"""
322. 零钱兑换
给你一个整数数组 coins ，表示不同面额的硬币；以及一个整数 amount ，表示总金额。
计算并返回可以凑成总金额所需的 最少的硬币个数 。如果没有任何一种硬币组合能组成总金额，返回 -1 。
你可以认为每种硬币的数量是无限的。
"""
import sys
from typing import List


class Solution:
    """
    方法一，备忘录递归
    """
    def coinChange1(self, coins: List[int], amount: int) -> int:
        memo = [0 for i in range(amount + 1)]
        return self.helper(coins, amount, memo)


    def helper(self, coins: List[int], amount: int, memo: List[int]) -> int:
        if amount == 0:
            return 0
        if amount < 0:
            return -1
        # 先查备忘录
        if memo[amount] != 0:
            return memo[amount]

        # 备忘录没有，直接计算
        res = sys.maxsize
        for coin in coins:
            dp = self.helper(coins, amount - coin, memo)
            if dp < 0:
                continue
            res = min(res, dp + 1)
        # 存储
        memo[amount] = -1 if res == sys.maxsize else res
        return memo[amount]

    """
    方法二，动态规划
    """
    def coinChange(self, coins: List[int], amount: int) -> int:
        if amount == 0:
            return 0
        if amount < 0:
            return -1
        dp = [amount + 1 for i in range(amount + 1)]
        dp[0] = 0
        for i in range(1, amount + 1):
            for coin in coins:
                if i - coin < 0:
                    continue
                dp[i] = min(dp[i], dp[i - coin] + 1)
        return -1 if dp[amount] == amount + 1 else dp[amount]